/**
 * Description: UNIX本地通信客户端--UDP协议
 * File: udp_server.c |Time: 2021-04-12 13:48
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <sys/un.h>
#include <strings.h>

#define N 100

#define ERR(msg) do {          \
            perror(msg);        \
            printf("%s:%s:%d\n", __FILE__, __func__, __LINE__); \
            exit(EXIT_FAILURE); \
        }while(0)



int main(int argc, char *argv[])
{
    if (argc < 3) {
        printf("Usage %s <server socket filename> <client socket filename>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int sockfd = socket(AF_UNIX, SOCK_DGRAM, 0);
    char buff[N] = {0};

    struct sockaddr_un serveraddr, clientaddr;
    socklen_t addrlen = sizeof(struct sockaddr_un);
    serveraddr.sun_family = AF_UNIX;
    strcpy(serveraddr.sun_path, argv[1]);

    // 如果客户端需要通过本地socket发送信息， 客户端需要绑定自己的socket信息
    clientaddr.sun_family = AF_UNIX;
    strcpy(clientaddr.sun_path, argv[2]);
    if (-1 == bind(sockfd, (struct sockaddr *)&clientaddr, addrlen))
    {
        ERR("bind");
    }

    printf("client ready.\n");

    while(1) {
        bzero(buff, N);
        printf("[to server]: ");
        fgets(buff, sizeof(buff), stdin);
        buff[strlen(buff) - 1] = '\0';
        sendto(sockfd, buff, N, 0, 
            (struct sockaddr *)&serveraddr, sizeof(serveraddr));

        recvfrom(sockfd, buff, N, 0, 
                (struct sockaddr *)&serveraddr, &addrlen);

        printf("[from server]: %s\n", buff);
    }


    return 0;
}
